<template>
  <eip-modal
    :visible="visible"
    :title="'关联' + record.options.title"
    @close="cancel"
    :position="position"
    :height="eipTableHeight() - 170"
    width="98%"
  >
    <template slot="body">
      <div class="padding-top-xs text-center">
        <a-spin :spinning="grid.loading">
          <vxe-grid
            v-if="!grid.loading"
            v-bind="grid"
            ref="chosenGrid"
            @radio-change="radioChange"
          >
            <template #toolbar_buttons
              ><label>已选中（{{ data.length }}）个</label>
            </template>
            <template #toolbar_tools> </template>
            <template #loading>
              <a-spin></a-spin>
            </template>
            <template #empty>
              <eip-empty />
            </template>
            <template #checkboxHeader="{ checked, indeterminate }">
              <span @click.stop="checkboxAllChange">
                <a-checkbox :indeterminate="indeterminate" :checked="checked">
                </a-checkbox>
              </span>
            </template>
            <!-- 多选 -->
            <template #checkbox="{ row, checked, indeterminate }">
              <span @click.stop="checkboxChange({ row })">
                <a-checkbox :indeterminate="indeterminate" :checked="checked">
                </a-checkbox>
              </span>
            </template>
            <!-- 单选 -->
            <template #radio="{ checked }">
              <span>
                <a-radio :checked="checked"> </a-radio>
              </span>
            </template>
            <!-- 序号 -->
            <template #seq="">
              <span>序号</span>
            </template>
            <template #seqdefalut="{ row }">
              {{ row.row_num }}
            </template>
            <!-- 格式化内容 -->
            <template #default="{ row, column }">
              <list-content
                :row="row"
                :column="column"
                :type="convertType(column)"
                :options="getOptions(column)"
              ></list-content>
            </template>
          </vxe-grid>
        </a-spin>
      </div>
      <worksheet-run
        ref="worksheet-run"
        v-if="worksheetRun.visible"
        :options="{
          rowId: worksheetRun.rowId,
          rowIds: [],
          zeroCodeId: record.options.zeroCodeId,
          mode: eipZeroCodeWorkSheetMode.add,
          from: from,
        }"
        :visible.sync="worksheetRun.visible"
        @ok="worksheetOk"
      ></worksheet-run>
    </template>
    <template slot="footer">
      <div class="flex justify-between align-center">
        <div>
          <a-button
            key="submit"
            type="primary"
            @click="add"
            v-if="record.options.canAdd"
            ><a-icon type="plus" />新建{{ record.options.title }}</a-button
          >
        </div>
        <a-space>
          <a-button @click="cancel"><a-icon type="close" />关闭</a-button>
          <a-button key="submit" @click="comfirm" type="primary"
            ><a-icon type="save" />确定</a-button
          >
        </a-space>
      </div>
    </template>
  </eip-modal>
</template>

<script>
import {
  findById,
  gridCustomFindByKey,
  gridCustomSave,
  findCorrelationFilter,
} from "@/services/system/zerocode/run/edit";
import listContent from "@/pages/system/zerocode/run/components/list/content";
import worksheetRun from "@/pages/system/zerocode/run/worksheet";
import { VxeUI } from "vxe-pc-ui";
import { newGuid } from "@/utils/util";
import { mapGetters } from "vuex";
export default {
  name: "correlation-chosen",
  computed: {
    ...mapGetters("account", ["zeroCode"]),
  },
  data() {
    return {
      position: {
        top: null,
        left: "center",
      },
      grid: {
        loading: true,
      },
      columnJson: {}, //字段配置
      columns: [],
      data: [], //选中数据

      //编辑组件
      worksheetRun: {
        rowId: newGuid(),
        visible: false,
      },

      gridCustom: {
        fixedData: null,
        resizableData: null,
        sortData: null,
        visibleData: null,
      },
    };
  },
  components: {
    worksheetRun,
    listContent,
  },
  props: {
    visible: {
      type: Boolean,
      default: false,
    },
    record: Object,
    //来源参数
    from: {
      type: Object,
      default: () => ({
        zeroCodeId: null, //工作表
        key: null, //来源控件
        rowId: null, //来源数据RowId
        rowIds: [], //选中数据RowId
      }),
    },
  },
  created() {
    this.initGrid();
  },
  methods: {
    /**
     * 新增
     */
    add() {
      this.worksheetRun.visible = true;
    },
    /**
     * 初始化列表
     */
    initGrid() {
      let that = this;
      VxeUI.loading.open();
      var systemZeroCodeData = that.$utils.find(
        this.zeroCode,
        (f) => f.zeroCodeId == that.record.options.zeroCodeId
      );
      if (systemZeroCodeData) {
        setTimeout(() => {
          that.setGridOption(systemZeroCodeData);
        }, 10);
      } else {
        findById(that.record.options.zeroCodeId).then((result) => {
          that.setGridOption(result.data);
        });
      }
    },
    /**
     *
     */
    radioChange({
      newValue,
      oldValue,
      row,
      rowIndex,
      $rowIndex,
      column,
      columnIndex,
      $columnIndex,
      $event,
    }) {
      this.data = [newValue];
    },
    /**
     *
     * @param systemZeroCodeData
     */
    setGridOption(systemZeroCodeData) {
      let that = this;
      that.columnJson = JSON.parse(systemZeroCodeData.columnJson);
      that.initGridOption();
      that.initColumn();
    },

    /**
     *
     */
    worksheetOk() {
      this.worksheetChosen.visible = false;
      this.$refs.chosenGrid.commitProxy("query");
    },

    /**
     * 得到排序
     */
    initSorts() {
      //默认排序
      var defaultSort = [];
      return defaultSort;
    },

    /**
     *初始化列表配置项
     */
    initGridOption() {
      //默认排序
      let that = this;
      this.grid = {
        size: "",
        border: "",
        stripe: "",
        id: "chosenGrid",
        loading: true,
        height: this.eipTableHeight() - 300,
        sortConfig: {
          trigger: "cell",
          defaultSort: this.initSorts(),
          orders: ["desc", "asc", null],
          remote: true,
          multiple: true,
          chronological: true,
        },
        checkboxConfig: {
          reserve: true,
          trigger: "manual",
        },
        radioConfig: {
          reserve: true,
          trigger: "row",
        },
        expandConfig: {
          reserve: true,
        },
        rowConfig: {
          keyField: "RowId",
        },
        customConfig: {
          storage: true,
          mode: "popup",
          restoreStore({ storeData }) {
            return true;
          },
          updateStore({ id, type, storeData }) {
            let resizableData = that.$utils.merge(
              that.gridCustom.resizableData,
              storeData.resizableData
            );
            let fixedData = that.$utils.merge(
              that.gridCustom.fixedData,
              storeData.fixedData
            );
            let sortData = that.$utils.merge(
              that.gridCustom.sortData,
              storeData.sortData
            );
            let visibleData = that.$utils.merge(
              that.gridCustom.visibleData,
              storeData.visibleData
            );
            gridCustomSave({
              key:
                that.record.options.zeroCodeId +
                "_" +
                that.record.key +
                "_chosenCard",
              title: that.record.options.label,
              config: JSON.stringify({
                fixedData: fixedData,
                resizableData: resizableData,
                sortData: sortData,
                visibleData: visibleData,
              }),
            }).then((result) => {});
            return true;
          },
        },
        pagerConfig: {},
        printConfig: {},
        exportConfig: {},
        filterConfig: {
          remote: true,
        },
        toolbarConfig: {
          slots: {
            buttons: "toolbar_buttons",
            tools: "toolbar_tools",
          },
        },
        columns: [],
        proxyConfig: {
          seq: true,
          sort: true,
          filter: true,
          props: {
            result: "data",
            total: "count",
          },
          ajax: {
            query: ({ page, sorts, filters }) => {
              if (sorts.length == 0) {
                //再次找默认
                sorts = this.initSorts();
              }
              var gridSort = this.eipGridSort(sorts);
              return new Promise((resolve) => {
                findCorrelationFilter({
                  zeroCodeId: that.from.zeroCodeId,
                  current: page.currentPage,
                  size: page.pageSize,
                  timeStamp: that.$utils.timestamp(),
                  sort: gridSort ? gridSort : "id desc",
                  key: that.record.key,
                  filters: that.eipTableFilter(filters),
                }).then((result) => {
                  if (result.code == that.eipResultCode.success) {
                    resolve(result.data);
                  } else {
                    that.$message.error(result.msg);
                    resolve({
                      data: [],
                    });
                  }
                  setTimeout(() => {
                    that.grid.loading = false;
                  }, 10);
                });
              });
            },
          },
        },
      };
    },

    /**
     * 初始化列
     */
    async initColumn() {
      let that = this;
      this.grid.columns = [];
      let record = this.record;
      let columns = [];
      if (
        record.options.type == this.eipZeroCodeControlCorrelationType.multiple
      ) {
        columns.push({
          type: "checkbox",
          width: 50,
          align: "center",
          fixed: "left",
          resizable: false,
          slots: {
            checkbox: "checkbox",
            header: "checkboxHeader",
          },
        });
      } else {
        columns.push({
          type: "radio",
          width: 50,
          align: "center",
          fixed: "left",
          resizable: false,
          slots: {
            radio: "radio",
          },
        });
      }
      //是否显示序号
      columns.push({
        type: "seq",
        width: 60,
        fixed: "left",
        resizable: false,
        slots: {
          header: "seq",
          default: "seqdefalut",
        },
      });
      this.record.options.columns.forEach((item) => {
        let columnFind = that.$utils.find(
          that.columnJson,
          (f) => item == f.key
        );
        if (columnFind) {
          let column = {
            field: columnFind.key,
            title: columnFind.label,
            width: columnFind.width,
            sortable: true,
            slots: {},
            showOverflow: "ellipsis",
            filterRender: {
              name: "MLFilterRender",
            },
            filters: [
              {
                data: {
                  type: "input",
                  key: null,
                  op: "cn",
                  write: null,
                  options: [],
                },
              },
            ],
          };
          //处理格式化
          switch (columnFind.type) {
            case that.eipZeroCodeControl.radio:
            case that.eipZeroCodeControl.checkbox:
            case that.eipZeroCodeControl.select:
              let options = [];
              columnFind.options.options.forEach((element) => {
                options.push({
                  value: element.value,
                  label: element.label,
                  checked: false,
                  color: columnFind.options.optionsColor ? element.color : null,
                });
              });
              column.filters = [
                {
                  data: {
                    type: "select",
                    key: null,
                    op: "jcn",
                    write: null,
                    options: options,
                  },
                },
              ];
              break;
            case that.eipZeroCodeControl.number:
              column.filters = [
                {
                  data: {
                    type: "number",
                    op: "cn",
                    write: null,
                    min: null,
                    max: null,
                  },
                },
              ];
              break;
            case that.eipZeroCodeControl.switch:
              column.filters = [
                {
                  data: {
                    type: "switch",
                    key: null,
                    op: "cn",
                    write: null,
                    options: [
                      {
                        value: 1,
                        label: "是",
                        checked: false,
                        color: "red",
                      },
                      {
                        value: 0,
                        label: "否",
                        checked: false,
                        color: "#1890ff",
                      },
                    ],
                  },
                },
              ];
              break;
            case "rate":
              column.filters = [
                {
                  data: {
                    type: "number",
                    op: "cn",
                    write: null,
                    min: null,
                    max: null,
                  },
                },
              ];
              break;
            case "slider":
              column.filters = [
                {
                  data: {
                    type: "number",
                    op: "cn",
                    write: null,
                    min: null,
                    max: null,
                  },
                },
              ];
              break;
            case "uploadFile":
            case "uploadImg":
              break;
            case "editor":
              column.type = "html";
              break;
            case "date":
              column.filters = [
                {
                  data: {
                    type: "datetime",
                    op: "cn",
                    write: null,
                    min: null,
                    max: null,
                  },
                },
              ];
              break;
          }
          if (columnFind.type != "editor") {
            column.slots.default = "default";
          }
          columns.push(column);
        } else {
          //是否为系统字段
          var isSys = that.$utils.find(
            that.eipSystemFiled,
            (f) => f.key == item
          );

          if (isSys) {
            let column = {
              field: isSys.key,
              title: isSys.title,
              width: 160,
              sortable: true,
              slots: {},
              showOverflow: "ellipsis",
              filterRender: {
                name: "MLFilterRender",
              },
              filters: [
                {
                  data: {
                    type: "input",
                    key: null,
                    op: "cn",
                    write: null,
                    options: [],
                  },
                },
              ],
            };
            switch (item) {
              case "CreateTime":
              case "UpdateTime":
                column.filters = [
                  {
                    data: {
                      type: "datetime",
                      op: "cn",
                      write: null,
                      min: null,
                      max: null,
                    },
                  },
                ];
                columns.push(column);
                break;
              case "RowId":
                column.filters = [
                  {
                    data: {
                      type: "input",
                      key: null,
                      op: "cn",
                      write: null,
                      options: [],
                    },
                  },
                ];
                columns.push(column);
                break;
              case "CreateUser":
              case "UpdateUser":
                column.filters = [
                  {
                    data: {
                      type: "user",
                      op: "cn",
                      write: null,
                    },
                  },
                ];
                column.slots.default = "default";
                columns.push(column);
                break;
            }
          }
        }
      });

      //获取grid
      var gridCustom = await gridCustomFindByKey(
        this.record.options.zeroCodeId + "_" + this.record.key + "_chosenCard"
      );
      if (gridCustom.data != null && gridCustom.data.config != null) {
        var config = JSON.parse(gridCustom.data.config);
        if (config.resizableData) {
          var resizableDataKey = that.$utils.keys(config.resizableData);
          resizableDataKey.forEach((key) => {
            var columnsFind = that.$utils.find(columns, (f) => f.field == key);
            if (columnsFind) {
              columnsFind.width = config.resizableData[key];
            }
          });
          that.gridCustom.resizableData = config.resizableData;
        }
        //固定
        if (config.fixedData) {
          var fixedDataKey = that.$utils.keys(config.fixedData);
          fixedDataKey.forEach((key) => {
            var columnsFind = that.$utils.find(columns, (f) => f.field == key);
            if (columnsFind) {
              columnsFind.fixed = config.fixedData[key];
            }
          });
          that.gridCustom.fixedData = config.fixedData;
        }
        //隐藏显示
        if (config.visibleData) {
          var visibleDataKey = that.$utils.keys(config.visibleData);
          visibleDataKey.forEach((key) => {
            var columnsFind = that.$utils.find(columns, (f) => f.field == key);
            if (columnsFind) {
              columnsFind.visible = config.visibleData[key];
            }
          });
          that.gridCustom.visibleData = config.visibleData;
        }
        let cloneColumns = [];
        //顺序
        var sortDataKey = that.$utils.keys(config.sortData);
        if (config.sortData && sortDataKey.length > 0) {
          let sortArray = [];
          sortDataKey.forEach((key) => {
            sortArray.push({
              key: key,
              value: config.sortData[key],
            });
          });
          sortArray = that.$utils.orderBy(sortArray, "value");
          sortArray.forEach((sort) => {
            var columnsFind = that.$utils.find(
              columns,
              (f) => f.field == sort.key
            );
            if (columnsFind) {
              cloneColumns.push(columnsFind);
            }
          });
          columns = cloneColumns;
          that.gridCustom.sortData = config.sortData;
        }
      }

      that.grid.columns = columns;
      setTimeout(function () {
        that.grid.loading = false;
        VxeUI.loading.close();
      }, 100);
    },
    /**
     * 转换类型
     * @param row
     * @param column
     */
    convertType(column) {
      var columnFind = this.$utils.find(
        this.columnJson,
        (f) => f.key == column.field
      );
      if (columnFind) {
        return columnFind.type;
      } else {
        switch (column.field) {
          case "CreateTime":
          case "UpdateTime":
            return "systime";
          case "CreateUser":
          case "UpdateUser":
            return "sysuser";
        }
      }
    },

    /**
     * 得到Options
     * @param column
     */
    getOptions(column) {
      return this.$utils.find(this.columnJson, (f) => f.key == column.field);
    },

    /**
     * 取消
     */
    cancel() {
      this.$emit("update:visible", false);
    },

    /**
     * 确定
     */
    comfirm() {
      //判断是否选择了数据
      if (this.data.length == 0) {
        this.$message.error("请选择数据");
        return;
      }
      this.$emit("ok", this.data);
      this.cancel();
    },

    /**
     * 选中事件
     */
    checkboxChange({ row }) {
      this.$refs.chosenGrid.toggleCheckboxRow(row);
      //获取当前列表选中项
      let nowChosen = this.$refs.chosenGrid.getCheckboxRecords(true);
      //获取其他页显示项
      let otherChosen = this.$refs.chosenGrid.getCheckboxReserveRecords(true);
      this.data = nowChosen.concat(otherChosen);
    },

    /**
     * 选中所有事件
     */
    checkboxAllChange({}) {
      this.$refs.chosenGrid.toggleAllCheckboxRow();
      //获取当前列表选中项
      let nowChosen = this.$refs.chosenGrid.getCheckboxRecords(true);
      //获取其他页显示项
      let otherChosen = this.$refs.chosenGrid.getCheckboxReserveRecords(true);
      this.data = nowChosen.concat(otherChosen);
    },
  },
};
</script>
